﻿package org.jcms.web.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 验证码serlvet
 * @author 赵泽洋
 *
 */
public class ValidateCode extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final int WIDTH = 100;
	private static final int HEIGHT = 25;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ValidateCode() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		 
		BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = bufferedImage.getGraphics();
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, WIDTH, HEIGHT);

		g.setColor(Color.GREEN);
		Random random = new Random(System.currentTimeMillis());
		for (int i = 0; i < 5; ++i) {
			random.nextInt(WIDTH);
			random.nextInt(HEIGHT);
			g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT),
					random.nextInt(WIDTH), random.nextInt(HEIGHT));
		}

		int x = random.nextInt(100);
		int y = random.nextInt(10);
		g.setColor(Color.WHITE);
		g.setFont(new Font("宋体", Font.BOLD, HEIGHT - 10));

		StringBuilder sb = new StringBuilder();
		sb.append(x);
		sb.append(" + ");
		sb.append(y);
		sb.append(" = ?");

		g.drawString(sb.toString(), 10, 20);
		String result = String.valueOf(x + y);
		request.getSession().setAttribute("validetecode", result);
		//设置浏览器不被缓存，但还建议取验证码的时候加上随机参数
		response.addHeader("Expires","-1");
		response.addHeader("Cache-Control","no-cache");
		response.addHeader("Pragma","no-cache");
		
		response.setContentType("image/jpeg");
		ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
